<template>
	<div class="word-editor-container">
		<el-card class="box-card">
			<template #header>
				<div class="card-header">
					<h3>文件管理</h3>
				</div>
			</template>

			<!-- 筛选区域 - 重新设计 -->
			<div class="filter-section">
				<div class="filter-row">
					<div class="filter-item">
						<span class="label">学年：</span>
						<el-select
							v-model="filters.academicYear"
							placeholder="选择学年"
							size="default"
							clearable
						>
							<el-option
								v-for="year in ['2023-2024', '2022-2023', '2021-2022']"
								:key="year"
								:label="year"
								:value="year"
							/>
						</el-select>
					</div>
					<div class="filter-item">
						<span class="label">班级：</span>
						<el-select v-model="filters.classId" placeholder="选择班级" size="default" filterable clearable>
							<el-option
								v-for="cls in classList"
								:key="cls.classId"
								:label="`${cls.academy || ''}${cls.major || ''}${cls.grade || ''}级${cls.classname || '未知班级'}班`"
								:value="cls.classId"
							/>
						</el-select>
					</div>
					<div class="filter-item">
						<span class="label">科目：</span>
						<el-select v-model="filters.subjectId" placeholder="选择科目" size="default" filterable clearable>
							<el-option
								v-for="subject in subjectList"
								:key="subject.id"
								:label="subject.subject"
								:value="subject.id"
							/>
						</el-select>
					</div>
					<div class="filter-item">
						<el-button type="primary" @click="handleSearch">查询</el-button>
						<el-button @click="resetFilters">重置</el-button>
					</div>
				</div>
			</div>

			<!-- 操作按钮区域 -->
			<div class="operation-section">
				<el-button
					type="primary"
					@click="handleBatchDownload"
					:disabled="selectedFiles.length === 0"
				>
					批量下载
				</el-button>
				<el-button type="danger" @click="handleBatchDelete" :disabled="selectedFiles.length === 0">
					批量删除
				</el-button>
			</div>

			<!-- 文件列表 -->
			<div class="file-list">
				<el-table
					:data="fileList"
					border
					stripe
					style="width: 100%"
					v-loading="loading"
					@selection-change="handleSelectionChange"
				>
					<el-table-column type="selection" width="55" />
					<el-table-column type="index" label="序号" width="60" align="center" />
					<el-table-column prop="fileName" label="文件名称" min-width="220" />
					<el-table-column label="文件路径" min-width="220">
						<template #default="{ row }">
							{{ formatFilePath(row.filePath) }}
						</template>
					</el-table-column>
					<el-table-column prop="fileType" label="文件类型" width="120" />
					<!-- <el-table-column prop="isEnabled" label="是否启用" width="120">
						<template #default="{ row }">
							{{ row.isEnabled === 1 ? '是' : '否' }}
						</template>
					</el-table-column> -->
					<el-table-column prop="uploadTime" label="上传时间" width="180" />
					<el-table-column prop="userId" label="用户ID" width="120" />
					<el-table-column label="操作" width="150" align="center">
						<template #default="{ row }">
							<el-button type="primary" size="small" @click="downloadFile(row)">下载</el-button>
							<el-button type="danger" size="small" @click="deleteFile(row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div class="pagination-container">
					<el-pagination
						v-model:current-page="currentPage"
						v-model:page-size="pageSize"
						:page-sizes="[10, 20, 30, 50]"
						layout="total, sizes, prev, pager, next, jumper"
						:total="total"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div>
			</div>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getFileSpecificService, deleteFileService } from '@/api/file'
import { getClassnameListService } from '@/api/education/classname'
import { getSubjectListService } from '@/api/education/subject'

interface FileItem {
	id: number
	fileName: string
	filePath: string
	fileType: string
	isEnabled: number
	uploadTime: string
	userId: number
}

// 状态变量
const loading = ref(false)
const fileList = ref<FileItem[]>([])
const selectedFiles = ref<FileItem[]>([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选相关 - 重构为简单的值类型
const classList = ref<
	{ classId: number; classname: string; academy: string; major: string; grade: string }[]
>([])
const subjectList = ref<{ id: number; subject: string }[]>([])

// 筛选条件对象 - 使用简单值类型
const filters = reactive({
	academicYear: '', // 学年
	classId: null as number | null, // 班级ID
	subjectId: null as number | null // 科目ID
})

// 获取班级和科目数据
const fetchFilterData = async () => {
	try {
		const [classResponse, subjectResponse] = await Promise.all([
			getClassnameListService(),
			getSubjectListService()
		])
		if (classResponse.data.code === 1) {
			classList.value = classResponse.data.data
		}
		if (subjectResponse.data.code === 1) {
			subjectList.value = subjectResponse.data.data
		}
	} catch (error) {
		console.error('获取筛选数据失败:', error)
		ElMessage.error('获取筛选数据失败')
	}
}

// 获取文件列表 - 不带筛选
const fetchFileList = async () => {
	loading.value = true
	try {
		const response = await getFileSpecificService({
			fileType: 'document',
			page: currentPage.value,
			pageSize: pageSize.value
		})
		if (response.data.code === 1) {
			fileList.value = response.data.data
			total.value = response.data.data.length
		} else {
			ElMessage.error(response.data.msg || '获取文件列表失败')
		}
	} catch (error) {
		console.error('获取文件列表失败:', error)
		ElMessage.error('获取文件列表失败')
	} finally {
		loading.value = false
	}
}

// 执行搜索 - 应用筛选条件
const handleSearch = () => {
	console.log('执行搜索，筛选条件:', filters)
	loading.value = true

	// 构造查询参数
	const params: any = {
		fileType: 'document'
	}

	// 单独处理各个筛选条件，避免多余的分隔符
	// 如果只有学年
	if (filters.academicYear && !filters.classId && !filters.subjectId) {
		params.fileName = filters.academicYear
		console.log('只有学年筛选，文件名参数:', params.fileName)
	}
	// 如果只有班级
	else if (!filters.academicYear && filters.classId && !filters.subjectId) {
		const classInfo = classList.value.find((c) => c.classId === filters.classId)
		if (classInfo) {
			params.fileName = `${classInfo.academy || ''}-${classInfo.major || ''}-${classInfo.grade || ''}级-${classInfo.classname || '未知班级'}班`
			console.log('只有班级筛选，文件名参数:', params.fileName)
		}
	}
	// 如果只有科目
	else if (!filters.academicYear && !filters.classId && filters.subjectId) {
		const subjectInfo = subjectList.value.find((s) => s.id === filters.subjectId)
		if (subjectInfo) {
			params.fileName = subjectInfo.subject
			console.log('只有科目筛选，文件名参数:', params.fileName)
		}
	}
	// 组合条件情况
	else if (filters.academicYear || filters.classId || filters.subjectId) {
		// 构造符合后端标准格式的文件名
		let fileNameParts: string[] = []

		// 添加学年条件
		if (filters.academicYear) {
			fileNameParts.push(filters.academicYear)
		}

		// 添加班级条件 (学院-专业-年级-班级)
		if (filters.classId !== null) {
			const classInfo = classList.value.find((c) => c.classId === filters.classId)
			if (classInfo) {
				// 构造班级完整描述
				const classString = `${classInfo.academy || ''}-${classInfo.major || ''}-${classInfo.grade || ''}级-${classInfo.classname || '未知班级'}班`
				fileNameParts.push(classString)
			}
		}

		// 添加科目条件
		if (filters.subjectId !== null) {
			const subjectInfo = subjectList.value.find((s) => s.id === filters.subjectId)
			if (subjectInfo) {
				fileNameParts.push(subjectInfo.subject)
			}
		}

		// 构造文件名格式，只用非空值
		if (fileNameParts.length > 0) {
			params.fileName = fileNameParts.join('-')
			console.log('组合筛选，文件名参数:', params.fileName)
		}
	}

	console.log('API查询参数:', params)

	// 发送API请求
	getFileSpecificService(params)
		.then((response) => {
			if (response.data.code === 1) {
				fileList.value = response.data.data
				total.value = response.data.data.length

				// 如果结果为空，显示提示
				if (params.fileName && fileList.value.length === 0) {
					ElMessage.warning('没有符合筛选条件的数据')
				}
			} else {
				ElMessage.error(response.data.msg || '获取文件列表失败')
			}
			loading.value = false
		})
		.catch((error) => {
			console.error('搜索失败:', error)
			ElMessage.error('搜索失败')
			loading.value = false
		})
}

// 重置筛选条件
const resetFilters = () => {
	filters.academicYear = ''
	filters.classId = null
	filters.subjectId = null
	fetchFileList()
}

// 处理选择变化
const handleSelectionChange = (selection: FileItem[]) => {
	selectedFiles.value = selection
}

// 格式化文件路径
const formatFilePath = (path: string) => {
	const basePath = 'C:\\Users\\Max\\Desktop\\uploadFile'
	return basePath
}

// 下载单个文件
const downloadFile = async (file: FileItem) => {
	try {
		const link = document.createElement('a')
		link.href = `http://localhost:8899/api/public/uploads/${file.fileName}`
		link.download = file.fileName
		document.body.appendChild(link)
		link.click()
		document.body.removeChild(link)
		ElMessage.success('文件下载成功')
	} catch (error) {
		console.error('下载失败:', error)
		ElMessage.error('下载失败，请重试')
	}
}

// 批量下载
const handleBatchDownload = () => {
	if (selectedFiles.value.length === 0) {
		ElMessage.warning('请选择要下载的文件')
		return
	}
	selectedFiles.value.forEach((file) => {
		downloadFile(file)
	})
}

// 删除文件
const deleteFiles = (files: FileItem[]) => {
	const message = `确定要删除选中的 ${files.length} 个文件吗？`

	ElMessageBox.confirm(message, '删除确认', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			loading.value = true
			try {
				const ids = files.map((file) => file.id)
				const response = await deleteFileService(ids)
				if (response.data.code === 1) {
					await fetchFileList()
					ElMessage.success('删除成功')
				} else {
					ElMessage.error(response.data.msg || '删除失败')
				}
			} catch (error) {
				ElMessage.error('删除失败，请重试')
			} finally {
				loading.value = false
			}
		})
		.catch(() => {})
}

// 删除单个文件
const deleteFile = (file: FileItem) => {
	deleteFiles([file])
}

// 批量删除
const handleBatchDelete = () => {
	if (selectedFiles.value.length === 0) {
		ElMessage.warning('请选择要删除的文件')
		return
	}
	deleteFiles(selectedFiles.value)
}

// 分页处理
const handleSizeChange = (val: number) => {
	pageSize.value = val
	handleSearch()
}

const handleCurrentChange = (val: number) => {
	currentPage.value = val
	handleSearch()
}

onMounted(() => {
	fetchFilterData()
	fetchFileList()
})
</script>

<style scoped lang="scss">
.word-editor-container {
	padding: 20px;

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;

		h3 {
			margin: 0;
			color: var(--el-text-color-primary);
		}
	}

	.filter-section {
		margin-bottom: 20px;
		padding: 15px;
		background-color: var(--el-fill-color-light);
		border-radius: 4px;

		.filter-row {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			gap: 15px;

			.filter-item {
				display: flex;
				align-items: center;
				gap: 8px;

				.label {
					white-space: nowrap;
					color: var(--el-text-color-regular);
				}

				.el-select {
					width: 160px;
				}
			}
		}
	}

	.operation-section {
		margin-bottom: 20px;
		display: flex;
		gap: 10px;
	}

	.file-list {
		.pagination-container {
			margin-top: 20px;
			display: flex;
			justify-content: center;
		}
	}
}
</style>
